<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
    <title>ShellCheck: SC2063 – Grep uses regex, but this looks like a glob.</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
  </head>
  <body style="margin-left: auto; margin-right: auto; max-width: 800px">
    <h1>SC2063 – ShellCheck Wiki</h1>
    <a href="https://github.com/koalaman/shellcheck/wiki/SC2063">See this page on GitHub</a>
    <p style="display: none"><a href="index.html">Sitemap</a></p>
    <hr />
    <h2 id="grep-uses-regex-but-this-looks-like-a-glob">Grep uses regex, but
this looks like a glob.</h2>
<h3 id="problematic-code">Problematic code:</h3>
<div class="sourceCode" id="cb1"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb1-1"><a href="SC2063.html#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">grep</span> <span class="st">&#39;*foo*&#39;</span></span></code></pre></div>
<h3 id="correct-code">Correct code:</h3>
<div class="sourceCode" id="cb2"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb2-1"><a href="SC2063.html#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="fu">grep</span> <span class="st">&#39;foo&#39;</span>   <span class="co"># or more explicitly,  grep &#39;.*foo.*&#39;</span></span></code></pre></div>
<h3 id="rationale">Rationale:</h3>
<p>In globs, <code>*</code> matches any number of any character.</p>
<p>In regex, <code>*</code> matches any number of the preceding
character.</p>
<p><code>grep</code> uses regex, not globs, so this means that
<code>grep '*foo'</code> is nonsensical because there's no preceding
character for <code>*</code>.</p>
<p>If the intention was to match "any number of characters followed by
foo", use <code>'.*foo'</code>. Also note that since grep matches
substrings, this will match "fishfood". Use anchors to prevent this,
e.g. <code>foo$</code>.</p>
<p>This also means that <code>f*</code> will match "hello", because
<code>f*</code> matches 0 (or more) "f"s and there are indeed 0 "f"
characters in "hello". Again, use <code>grep 'f'</code> to find strings
containing "f", or <code>grep '^f'</code> to find strings starting with
"f".</p>
<h3 id="exceptions">Exceptions</h3>
<p>If you're aware of the differences between globs and regex, you can
ignore this message.</p>
    <hr />
    <p style='font-size: 80%'><a href="../index.html">ShellCheck</a> is a static analysis tool for shell scripts. This page is part of its documentation.</p>
  </body>
</html>


